package com.infoland.afanmall.model.story.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.fragment.BaseLazyFragment;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.CacheKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.StatusBarKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.base.view.refreshHeader.Header;
import com.infoland.afanmall.model.eventBus.main.RefBus;
import com.infoland.afanmall.model.story.activity.StoryInfoActivity;
import com.infoland.afanmall.model.story.adapter.StoryAdapter;
import com.infoland.afanmall.model.story.entity.StoryEntity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.jzvd.JZVideoPlayer;

/**
 * 故事Fragment
 */

public class StoryFragment extends BaseLazyFragment {
    Unbinder unbinder;
    @BindView(R.id.story_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.story_refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.avi_pt)
    AVLoadingIndicatorView aviPt;
    @BindView(R.id.zui_hou)
    LinearLayout zuiHou;
    //
    StoryAdapter storyAdapter; //适配器
    List<StoryEntity.ObjectBean.ListBean> list;

    int pageNumber;
    int pageSize = CONST.STORY_FRAGMENT_PAGE_SIZE;
    boolean isLastPage = false;//不是最后一页
    int time = 10 * 1000;

    public int getLayout() {
        return R.layout.story_fragment;
    }

    //  入口
    @Override
    public void initData() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(CacheKit.APP_CONTEXT));
        refreshLayout.setRefreshHeader(new Header(CacheKit.APP_CONTEXT));
        refreshLayout.setHeaderHeight(60);
        LogKit.E("StoryFragment ---->   ", "  StoryFragment");
        //触发自动刷新
//        refreshLayout.autoRefresh();
//        StatusBarKit.setPaddingSmart(getActivity(), refreshLayout);
        initAdapter();
        initPage();
        loadStory();
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            loadStory();
        });
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            refStory();
        });
    }

    //初始化适配器
    private void initAdapter() {
        storyAdapter = null;
        list = null;
        list = new ArrayList<>();
        storyAdapter = new StoryAdapter(list, Objects.requireNonNull(getActivity()).getApplicationContext(),
                mRecyclerView, StatusBarKit.getStatusBarHeight(getActivity()));
        clickBack();
        mRecyclerView.setAdapter(storyAdapter);
    }

    //点击事件回调
    private void clickBack() {
        storyAdapter.setCallBack((v, img_video, type, position, item) -> {
            Bundle bundle;
            switch (img_video) {
                /*** 图片**/
                case "img":
                    bundle = new Bundle();
                    bundle.putInt("id", item.getId());
                    ToolsKit.dongHua(getActivity(), StoryInfoActivity.class, bundle);
                    break;
                /*** 视频**/
                case "video":
                    switch (type) {
                        /*** 浏览量**/
                        case 0:
                            break;
                        /*** 评价**/
                        case 1:
                            break;
                        /*** 分享**/
                        case 2:
                            ToolsKit.openShareBottom((AppCompatActivity) getActivity());
                            break;
                        /*** 详情**/
                        default:
                            bundle = new Bundle();
                            bundle.putInt("id", item.getId());
                            ToolsKit.dongHua(getActivity(), StoryInfoActivity.class, bundle);
                            LogKit.E("   ", "  " + "  ");
                            break;
                    }
                    break;
            }

        });
    }

    //   加载数据请求
    private void loadStory() {
        refreshLayout.finishLoadMore(time);
        ToolsKit.openLoad(refreshLayout);
        if (nextPage()) {
            aviPt.setVisibility(View.VISIBLE);
            JSONObject para = getPagePara();
            new OkHttpKit().send(
                    response200 -> {
                        LogKit.E("loadStory ---->   ", "  " + response200);
                        StoryEntity storyEntity = JSON.parseObject(response200, StoryEntity.class);
                        if (storyEntity.isSuccess()) {
                            StoryEntity.ObjectBean object = storyEntity.getObject();
                            if (object != null) {
                                setPage(object.getPageNumber(), object.isLastPage());
                                loadData(object.getList());
                            }
                        } else {
                        }
                    },
                    success401 -> {

                    },
                    error -> {
                        ToastUtils.showShort("操作失败");
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();
                    }
                    , errorInternet -> {

                    }
            ).post(CONST.STORY_LIST, para, getActivity());
        }

    }

    //   更新数据
    private void loadData(List<StoryEntity.ObjectBean.ListBean> list) {
        storyAdapter.addData(list);
        storyAdapter.loadMoreComplete();
        aviPt.setVisibility(View.GONE);
        ToolsKit.openNormal(refreshLayout);
    }

    //   刷新数据请求
    private void refStory() {
        refreshLayout.finishRefresh(time);
        ToolsKit.openRef(refreshLayout);
        initPage();
        if (nextPage()) {
//        refreshLayout.setVisibility(View.GONE);
            aviPt.setVisibility(View.VISIBLE);
            JSONObject para = getPagePara();
            new OkHttpKit().send(
                    response200 -> {
                        LogKit.E("refStory ---->   ", "  " + response200);
                        StoryEntity storyEntity = JSON.parseObject(response200, StoryEntity.class);
                        if (storyEntity.isSuccess()) {
                            StoryEntity.ObjectBean object = storyEntity.getObject();
                            if (object != null) {
                                setPage(object.getPageNumber(), object.isLastPage());
                                refData(object.getList());
                                aviPt.setVisibility(View.GONE);
                            }
                        } else {
                        }
                    },
                    null,
                    error -> {
                        ToastUtils.showShort("操作超时");
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();
                    },
                    errorInternet -> {
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();
                        aviPt.setVisibility(View.GONE);
                    }
            ).post(CONST.STORY_LIST, para, getActivity());
        }
    }

    //   更新数据
    private void refData(List<StoryEntity.ObjectBean.ListBean> list) {
        LogKit.E("refData ---->   ", " refData ");
        new Handler().postDelayed(() -> {
            LogKit.E("Handler  ---->   ", "  refData");
            aviPt.setVisibility(View.GONE);
            initAdapter();
            storyAdapter.setNewData(list);
            storyAdapter.loadMoreComplete();
            ToolsKit.openNormal(refreshLayout);
        }, 500);
    }

    //初始化分页
    public void initPage() {
        zuiHou.setVisibility(View.GONE);
        pageNumber = 0;
        isLastPage = false;
        LogKit.E("initPage ---->   ", "pageNumber  " + pageNumber);

    }

    //下一页
    public boolean nextPage() {
        zuiHou.setVisibility(View.GONE);
        if (isLastPage) {
            zuiHou.setVisibility(View.VISIBLE);
            ToolsKit.showLastPage(refreshLayout, false);
            return false;
        } else {
            pageNumber += 1;
            return true;
        }
    }

    //请求结束，设置分页信息
    public void setPage(int pageNumber, Boolean isLastPage) {
        this.isLastPage = isLastPage;
        this.pageNumber = pageNumber;
    }

    // 获取分页参数
    private JSONObject getPagePara() {
        LogKit.E("aaaa ---->   ", "  获取分页参数");
        JSONObject para = new JSONObject();
        para.put("pageNumber", pageNumber);
        para.put("pageSize", pageSize);
        return para;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(getLayout(), container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        ToolsKit.deleteOKHttp(getActivity());
        unbinder.unbind();
        super.onDestroyView();
    }

    @Override
    public void onStart() {
        super.onStart();
//        EventBus.getDefault().register(getActivity());
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    //展示并刷新界面
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refAndShowLayout(RefBus refBus) {
        if (refBus != null) {
            if (refBus.getFragmentId() == 0) {
                LogKit.E("refAndShowLayout ---->   ", "  Story");
                refStory();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }
}